<template>
  <view class="uni-container">
    <uni-forms ref="form" :model="formData" validateTrigger="bind" label-width="120px">
      <uni-forms-item name="chapter_id" label="章节" required>
        <uni-data-picker v-model="formData.chapter_id" collection="mydb-course-chapter" field="title as text, _id as value"></uni-data-picker>
      </uni-forms-item>
      <uni-forms-item name="audiofile" label="原文音频文件" required>
        <uni-file-picker file-mediatype="all" return-type="array" v-model="formData.audiofile"></uni-file-picker>
      </uni-forms-item>
	  <uni-forms-item name="explain" label="原文内容">
	    <uni-easyinput placeholder="原文内容" v-model="formData.explain" type="textarea" trim="both"></uni-easyinput>
	  </uni-forms-item>
	<uni-forms-item v-for="(item,index) in dynamicLists" :key="item.id" :label="item.label+' '+(index+1)" required
		:rules="item.rules" :name="'files[' + item.id + ']'">
		<view class="form-item">
			<uni-easyinput v-model="dynamicFormData.names[item.id]" placeholder="请输入句子释义" />
			<uni-file-picker file-mediatype="all" return-type="array"
				v-model="dynamicFormData.files[item.id]"></uni-file-picker>
			<button class="button" size="mini" type="default" @click="del(item.id)">删除</button>
		</view>
	</uni-forms-item>
	<button type="warn" size="mini" @click="add">新增句子</button>
      <uni-forms-item name="imgfile" label="图片文件">
        <uni-file-picker file-mediatype="image" return-type="object" v-model="formData.imgfile"></uni-file-picker>
      </uni-forms-item>
      <uni-forms-item name="sort" label="排序">
        <uni-easyinput placeholder="数字越小，排序越前" type="number" v-model="formData.sort"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="status" label="生效状态">
        <switch @change="binddata('status', $event.detail.value)" :checked="formData.status"></switch>
      </uni-forms-item>
      <uni-forms-item name="description" label="备注">
        <uni-easyinput placeholder="维护者自用描述" v-model="formData.description" trim="both"></uni-easyinput>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import { validator } from '../../js_sdk/validator/mydb-course-sentence.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'mydb-course-sentence';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  

  export default {
    data() {
      let formData = {
        "chapter_id": "",
        "audiofile": [],
        "sentence": [],
        "explain": "",
        "imgfile": null,
        "sort": null,
        "status": true,
        "description": ""
      }
      return {
        formData,
        formOptions: {},
		dynamicFormData: {
			names: {},
			files:{}
		},
		dynamicLists: [],
        rules: {
          ...getValidator(Object.keys(formData))
        }
      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      add() {
      	this.dynamicLists.push({
      		label: '逐句音频',
      		// rules: [{
      		// 	'required': true,
      		// 	errorMessage: '内容必填'
      		// }],
      		id: Date.now()
      	})
      },
      del(id) {
      	let index = this.dynamicLists.findIndex(v => v.id === id)
      	this.dynamicLists.splice(index, 1)
      },
      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
		let sentence=[]
		this.dynamicLists.forEach((item)=>{
			sentence.push({
				name:this.dynamicFormData.names[item.id],
				file:this.dynamicFormData.files[item.id],
			})
		})
		
        this.$refs.form.validate().then((res) => {
			res.sentence=sentence
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).add(value).then((res) => {
          uni.showToast({
            title: '新增成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      }
    }
  }
</script>
